package com.mark.controller.protal;

import com.lly835.bestpay.model.PayResponse;
import com.mark.dto.OrderDTO;
import com.mark.enums.ResultEnum;
import com.mark.exception.SellException;
import com.mark.service.IOrderService;
import com.mark.service.IPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.net.URLDecoder;
import java.util.Map;

/**
 * Created by Choisaaaa on 2018/6/27.
 *支付
 */
@Controller
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private IOrderService iOrderService;

    @Autowired
    private IPayService iPayService;

    //1.发起支付
    @GetMapping("/create")
    public ModelAndView create(@RequestParam(value = "orderId") String orderId,
                               @RequestParam(value = "returnUrl") String returnUrl,
                               Map<String,Object> map) {
        //1.查询订单
        OrderDTO orderDTO = iOrderService.findOne(orderId);
        if (null == orderDTO) {
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        PayResponse payResponse = iPayService.create(orderDTO);
        returnUrl = URLDecoder.decode(returnUrl);
        map.put("payResponse",payResponse);
        map.put("returnUrl",returnUrl);

        return new ModelAndView("pay/create",map);
    }

    //2 接收回调:为微信回调回来的XML格式文件
    @PostMapping("/notify")
    public ModelAndView noitify(@RequestBody String notifyData) {
        //更新数据库信息

        iPayService.asyncNotify(notifyData);

        //返回给微信处理结果
        return new ModelAndView("pay/success");
    }
}
